#include "jsz_translator.h"
#ifdef _WIN32
#include <windows.h>
#endif

/**
 * 获取可执行文件所在目录
 */
char* get_executable_directory(const char* argv0) {
    char* exe_dir = malloc(MAX_PATH_LENGTH);
    if (!exe_dir) {
        return NULL;
    }
    
#ifdef _WIN32
    // 在Windows上使用GetModuleFileName获取真实的可执行文件路径
    char exe_path[MAX_PATH_LENGTH];
    DWORD result = GetModuleFileNameA(NULL, exe_path, MAX_PATH_LENGTH);
    if (result == 0 || result == MAX_PATH_LENGTH) {
        // 如果GetModuleFileName失败，回退到使用argv[0]
        strncpy(exe_path, argv0, MAX_PATH_LENGTH - 1);
        exe_path[MAX_PATH_LENGTH - 1] = '\0';
    }
#else
    // 在非Windows系统上使用argv[0]
    char exe_path[MAX_PATH_LENGTH];
    strncpy(exe_path, argv0, MAX_PATH_LENGTH - 1);
    exe_path[MAX_PATH_LENGTH - 1] = '\0';
#endif
    
    // 复制路径到结果缓冲区
    strncpy(exe_dir, exe_path, MAX_PATH_LENGTH - 1);
    exe_dir[MAX_PATH_LENGTH - 1] = '\0';
    
    // 查找最后一个路径分隔符
    char* last_slash = strrchr(exe_dir, '\\');
    char* last_forward_slash = strrchr(exe_dir, '/');
    
    // 选择最后出现的分隔符
    char* last_separator = last_slash;
    if (last_forward_slash && (!last_slash || last_forward_slash > last_slash)) {
        last_separator = last_forward_slash;
    }
    
    if (last_separator) {
        // 截断到目录部分
        *(last_separator + 1) = '\0';
    } else {
        // 如果没有找到分隔符，使用当前目录
        strcpy(exe_dir, ".\\");
    }
    
    return exe_dir;
}

/**
 * 构建配置文件的完整路径
 */
char* build_config_file_path(const char* argv0, const char* filename) {
    char* exe_dir = get_executable_directory(argv0);
    if (!exe_dir) {
        return NULL;
    }
    
    char* full_path = malloc(MAX_PATH_LENGTH);
    if (!full_path) {
        free(exe_dir);
        return NULL;
    }
    
    // 构建完整路径
    snprintf(full_path, MAX_PATH_LENGTH, "%s%s", exe_dir, filename);
    
    free(exe_dir);
    return full_path;
}

/**
 * 生成默认输出文件名
 */
char* generate_output_filename(const char* input_filename) {
    size_t len = strlen(input_filename);
    char* output_filename = malloc(len + 10); // 额外空间用于扩展名
    if (!output_filename) {
        return NULL;
    }
    
    strcpy(output_filename, input_filename);
    
    // 查找最后一个点的位置
    char* last_dot = strrchr(output_filename, '.');
    if (last_dot && strcmp(last_dot, ".jsz") == 0) {
        // 如果是.jsz文件，替换为.js
        strcpy(last_dot, ".js");
    } else {
        // 否则直接添加.js
        strcat(output_filename, ".js");
    }
    
    return output_filename;
}

/**
 * 检查文件是否存在
 */
bool file_exists(const char* filename) {
    FILE* file = fopen(filename, "r");
    if (file) {
        fclose(file);
        return true;
    }
    return false;
}

/**
 * 主函数
 */
int main(int argc, char* argv[]) {
    const char* input_file = NULL;
    const char* output_file = NULL;
    char* config_file = NULL;
    char* message_file = NULL;
    bool config_file_allocated = false;
    bool message_file_allocated = false;
    
    // 生成默认配置文件路径（从可执行文件目录）
    config_file = build_config_file_path(argv[0], DEFAULT_CONFIG_FILENAME);
    message_file = build_config_file_path(argv[0], DEFAULT_MESSAGE_FILENAME);
    
    if (!config_file || !message_file) {
        fprintf(stderr, "Error: Failed to build config file paths\n");
        if (config_file) free(config_file);
        if (message_file) free(message_file);
        return 1;
    }
    
    config_file_allocated = true;
    message_file_allocated = true;
    
    // 首先加载消息配置文件
    if (!load_messages_from_config(message_file)) {
        fprintf(stderr, "Warning: Failed to load message file '%s', using default messages\n", message_file);
    }
    
    // 解析命令行参数
    for (int i = 1; i < argc; i++) {
        if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) {
            print_usage(argv[0]);
            if (config_file_allocated) free(config_file);
            if (message_file_allocated) free(message_file);
            free_messages();
            return 0;
        } else if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--version") == 0) {
            print_version();
            if (config_file_allocated) free(config_file);
            if (message_file_allocated) free(message_file);
            free_messages();
            return 0;
        } else if (strcmp(argv[i], "-c") == 0 || strcmp(argv[i], "--config") == 0) {
            if (i + 1 < argc) {
                // 释放默认分配的配置文件路径
                if (config_file_allocated) {
                    free(config_file);
                    config_file_allocated = false;
                }
                config_file = argv[++i];
            } else {
                fprintf(stderr, "%s\n", get_message("ERROR_CONFIG_MISSING"));
                if (config_file_allocated) free(config_file);
                if (message_file_allocated) free(message_file);
                free_messages();
                return 1;
            }
        } else if (!input_file) {
            input_file = argv[i];
        } else if (!output_file) {
            output_file = argv[i];
        } else {
            fprintf(stderr, "%s\n", get_message("ERROR_TOO_MANY_ARGS"));
            print_usage(argv[0]);
            if (config_file_allocated) free(config_file);
            if (message_file_allocated) free(message_file);
            free_messages();
            return 1;
        }
    }
    
    // 检查必需的参数
    if (!input_file) {
        fprintf(stderr, "%s\n", get_message("ERROR_NO_INPUT_FILE"));
        print_usage(argv[0]);
        if (config_file_allocated) free(config_file);
        if (message_file_allocated) free(message_file);
        free_messages();
        return 1;
    }
    
    // 检查输入文件是否存在
    if (!file_exists(input_file)) {
        fprintf(stderr, get_message("ERROR_INPUT_NOT_EXIST"), input_file);
        fprintf(stderr, "\n");
        if (config_file_allocated) free(config_file);
        if (message_file_allocated) free(message_file);
        free_messages();
        return 1;
    }
    
    // 生成默认输出文件名
    char* generated_output = NULL;
    if (!output_file) {
        generated_output = generate_output_filename(input_file);
        if (!generated_output) {
            fprintf(stderr, "%s\n", get_message("ERROR_GENERATE_OUTPUT"));
            if (config_file_allocated) free(config_file);
            if (message_file_allocated) free(message_file);
            free_messages();
            return 1;
        }
        output_file = generated_output;
    }
    
    // 加载配置文件
    printf(get_message("INFO_LOADING_CONFIG"), config_file);
    printf("\n");
    if (!load_keywords_from_config(config_file)) {
        if (generated_output) {
            free(generated_output);
        }
        if (config_file_allocated) free(config_file);
        if (message_file_allocated) free(message_file);
        free_messages();
        return 1;
    }
    
    printf("%s\n", get_message("PROGRAM_HEADER"));
    printf(get_message("INFO_INPUT_FILE"), input_file);
    printf("\n");
    printf(get_message("INFO_OUTPUT_FILE"), output_file);
    printf("\n");
    printf("%s\n", get_message("SEPARATOR"));
    
    // 执行翻译
    bool success = translate_jsz_to_js(input_file, output_file);
    
    // 清理内存
    if (generated_output) {
        free(generated_output);
    }
    if (config_file_allocated) {
        free(config_file);
    }
    if (message_file_allocated) {
        free(message_file);
    }
    free_keywords();
    
    if (success) {
        printf("%s\n", get_message("SEPARATOR"));
        printf("%s\n", get_message("SUCCESS_COMPLETE"));
        free_messages();
        return 0;
    } else {
        printf("%s\n", get_message("SEPARATOR"));
        printf("%s\n", get_message("ERROR_FAILED"));
        free_messages();
        return 1;
    }
}